﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Xml;
using com.lover.astd.common.manager;
using com.lover.astd.common.model;
using com.lover.common;

namespace com.lover.astd.common.logic
{
    public class ProtocolMgr
    {
        private User _user;
        private ILogger _logger;
        public ILogger logger { get { return _logger; } }
        private IServer _logic;
        private string _gameUrl;
        private string _jsessionId;
        private List<Cookie> _cookies = new List<Cookie>();
        public User getUser() { return _user; }
        public ProtocolMgr(User u, ILogger logger, IServer logic, string gameUrl, string jsessionId)
        {
            _user = u;
            _logger = logger;
            _logic = logic;
            _gameUrl = gameUrl;
            Uri uri = new Uri(_gameUrl);
            _gameUrl = String.Format("{0}://{1}", uri.Scheme, uri.Host);
            _jsessionId = jsessionId;

            _cookies.Clear();
            Uri game_uri = new Uri(gameUrl);
            Cookie cook = new Cookie();
            cook.Path = "/root";
            cook.Domain = game_uri.Host;
            cook.Name = "JSESSIONID";
            cook.Value = jsessionId;
            _cookies.Add(cook);
        }
        public ServerResult getXml(string url, string desc)
        {
            _logger.logSingle(desc);
            ServerResult result = doGet(url);
            if (result == null) return null;
            _logger.logDebug(result.getDebugInfo());
            if (!result.HttpSucceed)
            {
                _logger.logError("http网络失败, code=" + result.HttpCode);
                return null;
            }
            if (!result.CmdSucceed)
            {
                _logger.logError(String.Format("{0}错误, [{1}]", desc, result.CmdError));
                if (result.CmdError.Contains("连接已超时") || result.CmdError.Contains("用户已在别处登陆") || result.CmdError.Contains("验证码") ||
                    result.CmdError.Contains("連接已超時") || result.CmdError.Contains("用戶已在別處登錄") || result.CmdError.Contains("驗證碼"))
                {
                    _logic.startReLoginTimer();
                    _logic.stopServer();
                    return null;
                }
            }
            XmlNode playerinfo = result.CmdResult.SelectSingleNode("/results/playerupdateinfo");
            if (playerinfo != null)
            {
                _user.refreshPlayerInfo(playerinfo);
                if (_logic != null) _logic.refreshPlayerSafe();
            }
            XmlNode battleinfo = result.CmdResult.SelectSingleNode("/results/playerbattleinfo");
            if (battleinfo != null)
            {
                _user.refreshPlayerInfo(battleinfo);
                if (_logic != null) _logic.refreshPlayerSafe();
            }
            return result;
        }
        public ServerResult postXml(string url, string data, string desc)
        {
            _logger.logSingle(desc);
            ServerResult result = doPost(url, data);
            if (result == null) return null;
            _logger.logDebug(result.getDebugInfo());
            if (!result.HttpSucceed)
            {
                _logger.logError("http网络失败, code=" + result.HttpCode);
                return null;
            }
            if (!result.CmdSucceed)
            {
                _logger.logError(String.Format("{0}错误, [{1}]", desc, result.CmdError));
                if (result.CmdError.Contains("连接已超时") || result.CmdError.Contains("用户已在别处登陆") || result.CmdError.Contains("验证码") ||
                    result.CmdError.Contains("連接已超時") || result.CmdError.Contains("用戶已在別處登錄") || result.CmdError.Contains("驗證碼"))
                {
                    _logic.startReLoginTimer();
                    _logic.stopServer();
                    return null;
                }
            }
            XmlNode playerinfo = result.CmdResult.SelectSingleNode("/results/playerupdateinfo");
            if (playerinfo != null)
            {
                _user.refreshPlayerInfo(playerinfo);
                if (_logic != null) _logic.refreshPlayerSafe();
            }
            XmlNode battleinfo = result.CmdResult.SelectSingleNode("/results/playerbattleinfo");
            if (battleinfo != null)
            {
                _user.refreshPlayerInfo(battleinfo);
                if (_logic != null) _logic.refreshPlayerSafe();
            }
            return result;
        }
        protected bool ifSuccess(XmlDocument doc)
        {
            XmlNode node = doc.SelectSingleNode("/results/state");
            return node.InnerText == "1";
        }
        private ServerResult doGet(string url)
        {
            string surl = String.Format("{0}{1}?{2}", _gameUrl, url, TimeMgr.TimeStamp);
            _logger.logDebug(String.Format("get url={0}", surl));
            ServerResult result = null;
            try
            {
                string retstr = TransferMgr.doGet(surl, ref _cookies);
                result = new ServerResult(retstr);
            }
            catch (System.Exception ex)
            {
                _logger.logError(ex.Message);
            }
            return result;
        }
        private ServerResult doPost(string url, string data)
        {
            string surl = String.Format("{0}{1}?{2}", _gameUrl, url, TimeMgr.TimeStamp);
            _logger.logDebug(String.Format("post url={0}, data={1}", surl, data));
            ServerResult result = null;
            try
            {
                string retstr = TransferMgr.doPost(surl, data, ref _cookies);
                result = new ServerResult(retstr);
            }
            catch (System.Exception ex)
            {
                _logger.logError(ex.Message);
            }
            return result;
        }
    }
}
